# -*- coding: utf-8 -*-

import pandas as pd


def  GetData(iid: str,db,db_type: str ="postgresql",bd:str="2024-01-01",
             ed:str="2024-01-31",return_type:str ='df'):
    """根据 db_type 调用不同的函数"""
    if db_type in ['postgresql','pg','postgres']:
        return GetDataFromPg(iid,db,bd,ed,return_type)


def GetDataFromPg(iid: str,db,bd,ed,return_type:str ='df'):
    """从 postgresql 读取数据"""
    sql=f"""SELECT to_char("DateTime", 'YYYY-MM-DD HH24:MI:SS') AS datetime, 
    "Instrument", "Open", "High", "Low","Close","Volume", "OpenInterest", "TradingDay"
    FROM future.future_min
    WHERE "TradingDay" >= '{bd}' AND "Instrument" ='{iid}')
    ORDER BY "DateTime" 
    """
    df=pd.read_sql(sql,db)
    if return_type in ['df','dataframe']:
        return df
    else:
        return df.to_dict(orient='records')
    
def  GetTickData(iid: str,db,db_type: str ="postgresql",bd:str="2024-01-01",
             ed:str="2024-01-31",return_type:str ='df'):
    """根据 db_type 调用不同的函数"""
    if db_type in ['postgresql','pg','postgres']:
        return GetTickDataFromPg(iid,db,bd,ed,return_type)


def GetTickDataFromPg(iid: str,db,bd,ed,return_type:str ='df'):
    """从 postgresql 读取数据"""
    sql=f"""SELECT to_char("DateTime", 'YYYY-MM-DD HH24:MI:SS') AS datetime, 
    "Instrument", "Open", "High", "Low","Close","Volume", "OpenInterest", "TradingDay"
    FROM future.future_min
    WHERE "TradingDay" >= '{bd}' AND "Instrument" ='{iid}')
    ORDER BY "DateTime" 
    """
    df=pd.read_sql(sql,db)
    if return_type in ['df','dataframe']:
        return df
    else:
        return df.to_dict(orient='records')